<template>
  <el-container class="GoodsModify">
    <el-header class="mt20 flex">
      <span class="title fs18">{{ pageTitle }}</span>
      <el-divider />
    </el-header>
    <el-main>
      <el-form ref="ruleForm" :model="form" label-width="110px" status-icon :rules="rules" label-position="right">
        <el-form-item label="上架时间">
          <span style="color: #606266;">{{ form.createTime | setTimeMini }}</span>
        </el-form-item>
        <el-form-item label="商品封面" prop="newIconId">
          <CuploadImageOnce :external-image-url.sync="form.newIconId" @onSuccess="(value) => { onSuccess('newIconId', value) }" />
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="商品标签" prop="hot">
          <el-input v-model="form.hot" placeholder="请输入商品标签，最大长度10个字符" maxlength="10" show-word-limit clearable />
        </el-form-item>
        <el-form-item label="商品类别" prop="parentIdList">
          <CcategoryCascader :category-id.sync="form.parentIdList" />
        </el-form-item>
        <el-form-item label="商品总库存" prop="stock_num">
          <el-input v-model="form.stock_num" placeholder="请输入商品总库存数量" type="number" clearable class="filterInputNumber" />
        </el-form-item>
        <el-form-item label="商品原价">
          <el-input v-model="form.oldPrice" placeholder="请输入商品原价" type="number" clearable class="filterInputNumber" />
        </el-form-item>
        <el-form-item label="商品现价" prop="price">
          <el-input v-model="form.price" placeholder="请输入商品现价" type="number" clearable class="filterInputNumber" />
        </el-form-item>
        <el-form-item label="商品展示图片" prop="homeImageIds">
          <CuploadImageList :file-list.sync="form.homeImageIds" @remove="removeIds" @onSuccess="(value) => { onSuccess('homeImageIds', value) }" />
        </el-form-item>
        <el-form-item label="商品详情图片" prop="detailsImageIds">
          <CuploadImageList :file-list.sync="form.detailsImageIds" @remove="removeIds" @onSuccess="(value) => { onSuccess('detailsImageIds', value) }" />
        </el-form-item>
        <el-form-item class="hanbleButton" label="操作">
          <el-button type="primary" size="medium" @click="submitSaveAddSku">保存并继续添加规格信息</el-button>
          <el-button size="medium" @click="submitSave">保存不添加规格信息</el-button>
        </el-form-item>
        <el-form-item v-if="!form.none_sku" label="商品sku规格" class="goodsSku">
          <el-drag-select v-model="selectSku" multiple placeholder="请选择要添加的商品规格类目" style="width: 300px;max-width: 100%;" @change="selectSkuChange" @dragChange="selectSkuChange">
            <el-option
              v-for="item in skuList"
              :key="item.k_s"
              :label="item.k"
              :value="item.k_s"
            />
          </el-drag-select>
          <div style="color:#909399;">请在第一个规格上传预览显示的规格类目图片</div>
          <el-divider />
          <div v-for="(item, index) in form.skuList" :key="index">
            <div class="mb10">
              <span style="color: #606266;">规格：<span style="color:#E6A23C;" class="bold fs16">{{ item.k }}</span></span>
            </div>
            <div class="flex mb15">
              <el-tag
                v-for="it in item.v"
                :key="it.id"
                effect="plain"
                class="tagSku flexCenter"
              >
                <Cimage v-if="it.previewImgUrl" :preview-src-list="[it.previewImgUrl[0].url]" :src="it.previewImgUrl[0].url" width="38px" height="38px" fit="cover" />
                <span class="ml5 mr5 fs14">{{ it.name }}</span>
                <i class="el-icon-edit-outline fs15" @click="openDialog(it, 'modify', item.id)" />
                <el-popconfirm
                  title="确定要执行该操作吗？"
                  @confirm="hanbleGoodsSku(it, item.k_s)"
                >
                  <i slot="reference" class="el-icon-close fs15" />
                </el-popconfirm>
              </el-tag>
              <el-button size="medium" icon="el-icon-plus" type="primary" plain style="height: 38px;" @click="openDialog({}, 'add', item.id)">添 加</el-button>
            </div>
            <el-divider />
          </div>
          <el-tag v-if="form.skuList !== undefined && form.skuList.length === 0" type="danger">未有数据</el-tag>
        </el-form-item>
        <el-form-item v-if="!form.none_sku" label="商品规格列表">
          <el-button size="small" icon="el-icon-plus" type="primary" plain @click="openDialog({}, 'addSku')">新增规格列表</el-button>
          <el-table
            :data="form.list"
            style="width: 100%"
          >
            <el-table-column label="规格说明" align="center">
              <template slot-scope="{row}">
                <el-row v-for="item in row.data" :key="item.id">
                  <el-col :span="12" style="text-align: right;">{{ item.k | isNullData }}：</el-col>
                  <el-col :span="12" :style="{ textAlign: 'left', color: theme }">{{ item.name | isNullData }}</el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column prop="stock_num" label="该项库存" align="center">
              <template slot-scope="{row}">
                <span>{{ row.stock_num | isNullData }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="stock_num" label="该项价格" align="center">
              <template slot-scope="{row}">
                <span style="color:#F56C6C;">￥ {{ row.price | isNullData }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="{row}">
                <el-popconfirm
                  title="确定要执行该操作吗？"
                  @confirm="removeSkuList(row)"
                >
                  <el-button slot="reference" size="small" icon="el-icon-delete" type="danger">删 除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
    </el-main>
    <Cdialog
      :visible="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      class="GoodsModify-dialog"
      @handleClose="handleClose"
    >
      <div v-if="dialog.type === 'add' || dialog.type === 'modify'" class="GoodsModify-dialog-content flexColCenter pt5 pb5 pl10 pr10">
        <CuploadImageOnce :external-image-url.sync="dialog.item.previewImgId" />
        <Cinput v-model="dialog.item.name" placeholder="请输入类目名称" style="width: 100%;" class="mt30">输入类目名称</Cinput>
      </div>
      <div v-else class="GoodsModify-dialog-content pt15 pb5 pl10 pr10">
        <div v-for="item in form.skuList" :key="item.id" class="mb15 flex">
          <span class="mr15 mb5">{{ item.k | isNullData }}</span>
          <!-- 组件会自动新增vId这个字段 -->
          <el-radio-group v-if="item.v.length > 0" v-model="item.vId" size="medium" class="GoodsModify-dialog-content-group" @change="() => { addSkuChange(item) }">
            <el-radio-button v-for="it in item.v" :key="it.id" :label="it.id" :class="it.previewImgUrl ? 'previewImgUrlButton' : ''">
              <Cimage v-if="it.previewImgUrl" :src="it.previewImgUrl[0].url" width="36px" height="36px" fit="cover" class="mr10" />
              <span>{{ it.name | isNullData }}</span>
            </el-radio-button>
          </el-radio-group>
          <el-tag v-else type="danger">未有数据，请添加规格值</el-tag>
        </div>
        <Cinput v-model="dialog.stock_num" type="number" placeholder="库存" style="width: 100%;" class="mt30">输入该选项库存</Cinput>
        <Cinput v-model="dialog.price" type="number" placeholder="价格" style="width: 100%;" class="mt30">输入该选项价格</Cinput>
      </div>
      <div slot="footer" class="flexCenter">
        <el-button size="small" @click="handleClose">取 消</el-button>
        <el-button v-if="dialog.type === 'add' || dialog.type === 'modify'" type="primary" size="small" @click="saveSku">保 存</el-button>
        <el-button v-else type="primary" size="small" @click="submitAddSku">提 交</el-button>
      </div>
    </Cdialog>
  </el-container>
</template>
<script>
import {
  myGoodsDetail,
  myGoodsModify
} from '@/api/myGoods'
import CcategoryCascader from '@/components/CcategoryCascader'
import CuploadImageOnce from '@/components/CuploadImageOnce'
import CuploadImageList from '@/components/CuploadImageList'
import {
  goodsSkuListModifyList,
  goodsSkuListGetList,
  goodsSkuListDeleteList
} from '@/api/goodsSkuList'
import {
  goodsSkuGetSkuList,
  goodsSkuGetMyGoodsSku,
  goodsSkuTypeModifySkuType,
  goodsSkuTypeDeleteSku
} from '@/api/goodsSku'
import variables from '@/styles/element-variables.scss'
export default {
  components: { CcategoryCascader, CuploadImageOnce, CuploadImageList },
  data() {
    return {
      id: '', // 商品id
      type: '', // 页面类型
      deleteIds: [], // 要删除的商品展示图片ids
      form: { // 表单数据
        none_sku: true
      },
      dialog: { // 弹窗数据
        visible: false,
        title: '',
        width: '', // 宽度
        type: '', // 弹窗类型
        skuId: '', // sku大类id
        item: '', // 修改类目的item数据（用于规格类目）

        stock_num: '', // 增加规格列表的库存
        price: '', // 增加规格列表的价格
        skuValue: {} // 增加规格列表的选择的sku
      },

      selectSku: [], // 已选择的sku大类列表
      skuList: [], // sku大类数据

      rules: { // 校验规则
        newIconId: [{ required: true, message: '请上传封面', trigger: 'blur' }],
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        hot: [
          { required: true, message: '请输入商品标签', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        parentIdList: [{ required: true, message: '请选择商品类别', trigger: 'change' }],
        stock_num: [{ required: true, message: '请输入商品总库存', trigger: 'blur' }],
        price: [{ required: true, message: '请输入商品现价', trigger: 'blur' }],
        homeImageIds: [{ required: true, message: '请上传商品展示图片', trigger: 'blur' }],
        detailsImageIds: [{ required: true, message: '请上传商品详情图片', trigger: 'blur' }]
      },
      theme: variables.theme
    }
  },
  computed: {
    page() { // 页面类型
      return this.type === 'modify' ? 'modify' : 'add'
    },
    pageTitle() {
      return this.type === 'modify' ? '编辑商品' : '发布商品'
    }
  },
  created() {
    if (this.$route.query) {
      this.id = this.$route.query.id || ''
      this.type = this.$route.query.type
    }
    if (this.id) this.getDetails()
    this.getgoodsSkuGetSkuList()
  },
  methods: {
    // 级联选择器商品规格类目的修改删除 回调
    async selectSkuChange() {
      const res = await myGoodsModify({
        id: this.form.id,
        sku: this.selectSku.toString()
      })
      if (res.code === 0) {
        this.$message.success(res.msg)
        this.getgoodsSkuGetMyGoodsSku()
      }
    },
    // 对话框点击保存（商品规格）修改或增加sku小类规格id
    async saveSku() {
      if (!this.dialog.item.name) {
        this.$message.error('请输入类目名称')
        return
      }
      const res = await goodsSkuTypeModifySkuType({
        id: this.dialog.item.id ? this.dialog.item.id : undefined,
        skuId: this.dialog.skuId,
        goodsId: this.form.id,
        name: this.dialog.item.name,
        imgId: this.dialog.item.previewImgId
      })
      if (res.code === 0) {
        this.$message.success(res.msg)
        this.handleClose()
        this.getgoodsSkuGetMyGoodsSku()
        this.getgoodsSkuListGetList()
      }
    },
    // 删除单个规格列表
    async removeSkuList(row) {
      const res = await goodsSkuListDeleteList({ ids: row.id })
      if (res.code === 0) {
        this.$message.success(res.msg)
        this.getgoodsSkuListGetList()
      }
    },
    // 提交保存（新增规格列表）
    async submitAddSku() {
      // 如果对话框的sku对象值长度不够这个商品的规格列表长度（说明没有选完）
      if (Object.keys(this.dialog.skuValue).length !== this.form.skuList.length) {
        this.$message.error('请选择规格')
        return
      }
      if (!this.dialog.stock_num) {
        this.$message.error('请输入库存')
        return
      }
      if (!this.dialog.price) {
        this.$message.error('请输入价格')
        return
      }
      const res = await goodsSkuListModifyList({
        parentId: this.form.id,
        price: this.dialog.price,
        stock_num: this.dialog.stock_num,
        ...this.dialog.skuValue // 选择的sku
      })
      if (res.code === 0) {
        this.$message.success(res.msg)
        this.getgoodsSkuListGetList()
        this.handleClose()
      }
    },
    // 选择规格（新增规格列表）
    addSkuChange(item) {
      this.dialog.skuValue[item.k_s] = item.vId // 直接用对象方式（可以替换也可以增加）
    },
    // 提交保存(页面表单)
    submitSave() {
      this.form.none_sku = true // 是无规格商品
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          this.myGoodsModify()
        }
      })
    },
    // 提交保存（页面表单）+继续新增规格信息
    submitSaveAddSku() {
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          this.form.none_sku = false // 不是无规格商品
          this.myGoodsModify()
        }
      })
    },
    // 删除商品的类目Sku值
    async hanbleGoodsSku(item, key) {
      const res = await goodsSkuTypeDeleteSku({ id: item.id, key: key })
      if (res.code === 0) {
        this.$message.success(res.msg)
        this.getgoodsSkuGetMyGoodsSku()
        this.getgoodsSkuListGetList()
      }
    },
    // 关闭弹窗
    handleClose() {
      this.dialog = { // 弹窗数据
        visible: false,
        title: '',
        width: '', // 宽度
        type: '', // 弹窗类型
        skuId: '', // sku大类id
        item: '', // 修改类目的item数据

        stock_num: '', // 增加规格列表的库存
        price: '', // 增加规格列表的价格
        skuValue: {} // 增加规格列表的数据
      }
      // 顺便把el-radio-group组件生成的已选择的vId字段清除
      if (this.form.skuList !== undefined && this.form.skuList.length > 0) {
        this.form.skuList.forEach((item, index) => {
          if (item.vId) {
            delete item.vId
          }
        })
      }
    },
    // 打开弹窗
    openDialog(item, type, skuId) {
      item['previewImgId'] = ''
      switch (type) {
        case 'modify':
          this.dialog.title = '修改类目'
          this.dialog.width = '300px'
          if (item.previewImgUrl) item['previewImgId'] = item.previewImgUrl[0].url
          break
        case 'add':
          this.dialog.title = '新增类目'
          this.dialog.width = '300px'
          break
        case 'addSku':
          this.dialog.title = '新增规格列表'
          this.dialog.width = '600px'
          break
      }
      if (skuId) this.dialog.skuId = skuId
      this.dialog.type = type
      this.dialog.visible = true
      this.dialog.item = item
    },
    // 删除的商品展示图片ids回调
    removeIds(id) {
      const data = id.length <= 10 ? id : '' // 判断为网络资源地址（非自己服务器地址）
      this.deleteIds.push(data)
    },
    // 获取单个商品详情
    async getDetails() {
      const res = await myGoodsDetail({ goodsId: this.id })
      if (res.code === 0) {
        const { data } = res
        if (data.iconId && data.iconId.length > 0) { // 判断是否存在商品封面
          data['newIconId'] = data.iconId[0].url
        }
        if (data.parentId && data.fatherId) { // 判断返回了一二级分类id组成数组
          data['parentIdList'] = [data.fatherId.toString(), data.parentId.toString()] // 转成字符串，饿了么组件bug
        }
        if (data.list && data.list.length > 0) { // 格式化规格列表（匹配值）
          data.list.forEach(item => {
            item['data'] = []
            data.skuList.forEach(value => {
              item['data'] = this.formatSku(item, value)
            })
          })
        }
        if (data.sku) { // 初始化该商品选择的大类sku规格
          this.selectSku = data.sku.split(',')
        }
        this.form = data
        console.log(this.form, '数据')
      }
    },
    formatSku(item, skuItem) { // 格式化规格列表（匹配值）
      for (const prop in item) {
        for (const key in skuItem) {
          // eslint-disable-next-line eqeqeq
          if (prop == skuItem[key]) {
            const index = skuItem.v.findIndex(it => it.id === item[prop]) // 获取索引
            item['data'].push({
              k: skuItem.k,
              key: prop,
              id: item[prop],
              name: skuItem.v[index].name
            })
          }
        }
      }
      return item['data']
    },
    // 修改或新增商品接口
    async myGoodsModify() {
      const data = this._.cloneDeep(this.form) // 深克隆
      if (data.detailsImageIds && data.detailsImageIds.length > 0) { // 取得多个文件信息中的id
        data.detailsImageIds = data.detailsImageIds.map(item => item.id || item.response.data.id).toString()
      }
      if (data.homeImageIds && data.homeImageIds.length > 0) { // 取得多个文件信息中的id
        data.homeImageIds = data.homeImageIds.map(item => item.id || item.response.data.id).toString()
      }
      const res = await myGoodsModify({
        ...data,
        sku: this.selectSku.toString(),
        iconId: data.newIconId, // 商品封面id
        parentId: data.parentIdList.pop() // 商品的分类id
      })
      if (res.code === 0) {
        const { data } = res
        this.id = data.id // 重新赋值商品id（用于发布商品的重新刷新数据）
        this.$message.success(res.msg)
        this.getDetails() // 更新商品数据
      }
    },
    // 获取该商品的所有规格列表 （用于单独刷新数据）(不可在初始化使用)
    async getgoodsSkuListGetList() {
      const res = await goodsSkuListGetList({ goodsId: this.form.id })
      if (res.code === 0) {
        const { data } = res
        if (data && data.length > 0) { // 格式化规格列表（匹配值）
          data.forEach(item => {
            item['data'] = []
            this.form.skuList.forEach(value => {
              item['data'] = this.formatSku(item, value)
            })
          })
        }
        this.form['list'] = data
      }
    },
    // 获取商品的sku规格类目
    async getgoodsSkuGetMyGoodsSku() {
      const res = await goodsSkuGetMyGoodsSku({ goodsId: this.form.id })
      if (res.code === 0) {
        const { data } = res
        this.form['skuList'] = data
      }
    },
    // 获取sku大类数据
    async getgoodsSkuGetSkuList() {
      const res = await goodsSkuGetSkuList({
        page: 1,
        size: 9999
      })
      if (res.code === 0) {
        const { data } = res
        this.skuList = data.list
      }
    },
    // 上传成功回调（验证单个表单）
    onSuccess(type, value) {
      this.$refs.ruleForm.validateField(type) // 对部分表单字段进行校验的方法（自定义了组件，不会自动去验证）
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/styles/element-variables.scss";
.GoodsModify{
  .goodsSku{
    .tagSku{
      margin-right: 15px;
      letter-spacing: 2px;
      height: 40px;
      line-height: initial;
    }
    ::v-deep .el-icon-close{
      top: 0;
      font-size: 15px;
    }
    ::v-deep .el-icon-close:hover{
      color: #FFFFFF;
      background-color: $--color-primary;
    }
    ::v-deep .el-icon-edit-outline{
      cursor: pointer;
    }
    ::v-deep .el-icon-edit-outline:hover{
      color: #FFFFFF;
      background-color: $--color-primary;
    }
  }
  // 底部操作按钮
  .hanbleButton{
    ::v-deep .el-button{
      max-width: 100%;
    }
  }
}
.GoodsModify-dialog{
  &-content{
    width: 100%;
    height: 100%;
    &-group{
      ::v-deep .el-radio-button__inner{
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 14px;
        height: 36px;
        margin-bottom: 5px;
      }
    }
  }
}
.previewImgUrlButton{
  ::v-deep .el-radio-button__inner{
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    padding-right: 14px;
    height: 36px;
    margin-bottom: 5px;
  }
}
</style>
